from nicegui import app,ui
import os 
from functools import partial
import asyncio
with open('datapath.ini','r') as f:
    dataPath = f.read()

testDatas = []
def reNewData():
    global testDatas
    testDatas = os.listdir(dataPath)
    testDatas.sort(reverse=True)
reNewData()
#print(testDatas)
chosenData = os.path.join(dataPath,testDatas[0]) if testDatas else '未发现测试数据！'

ui.add_css('''
    .figure{
        width:600px;
        height:
           }
    .center{textalign:center;}
''')

with ui.header(elevated=True).style('background-color: #3874c8').classes('items-center justify-between'):
    ui.markdown('### starProbeAna').classes('')
    ui.button("刷新目录信息",on_click=reNewData)
    ui.space()
    ui.button('EXIT',on_click=app.shutdown)

dirlist = []
with ui.splitter(horizontal=False, reverse=False,value=18).classes("w-full") as splitter:
    
    with splitter.before:
        def visDir():
            for dapp in dirlist:
                dapp.visible=searchBox.value in dapp.text
        def classDir():
            for dapp in dirlist:
                if chosenData.split('\\')[-1].split('/')[-1] in dapp.text:
                    dapp.style('color:orange') 
                else:              
                    dapp.style('color:black')

        searchBox = ui.input('Search',placeholder='Input Keywords',on_change=visDir).classes('w-full')

        with ui.column() as menuDir:
            def renewMenu():
                menuDir.clear()
                reNewData()
                for dir in testDatas:
                    def changeSelect(dir):
                        global chosenData
                        chosenData = os.path.join(dataPath,dir)
                        pathLabel.text = chosenData
                        classDir()
                    dirlist.append(ui.label('🧰 '+dir).on('click',partial(changeSelect,dir)))
            renewMenu()
        classDir()
    with splitter.after:
        async def analysis(isforce = False):
            result.clear()
            waiting.visible = True
            await asyncio.sleep(0.1)
            import starfigure
            #参数表格
            
            para = starfigure.paraTable(chosenData,isforce)
            
            if para:
                paratable = ui.table(para['columns'],para['data']).classes('w-full')
                paratable.move(result)
            #转移特性曲线
            with ui.row() as transcurve:
                ui.space()
                ui.image(
                    starfigure.transcurve(chosenData,isforce)
                    ).classes("figure")
                ui.space()
            transcurve.move(result)
            
            if para:
                #有效率
                psucc = para['success']['PMOS']
                nsucc = para['success']['NMOS']
                ps,pa = psucc
                ns,na = nsucc
                with ui.splitter(horizontal=False, reverse=False,value=50).classes('w-full') as success: 
                    with success.before:
                        ui.echart({
                            "title":{
                                "text":"PMOS有效率{:.2f}%({}/{})".format(ps/pa*100,ps,pa)
                                },
                            "series":[{
                                
                                "type":"pie",
                                "data":[
                                    {"name":f"有效器件:{ps}个","value":f"{ps}"},
                                    {"name":f"失效器件：{pa-ps}个","value":f"{pa-ps}"}
                                ]
                            }]
                        })
                    with success.after:
                        ui.echart({
                            "title":{
                                "text":"NMOS有效率{:.2f}%({}/{})".format(ns/na*100,ns,na)
                                },
                            "series":[{
                                
                                "type":"pie",
                                "data":[
                                    {"name":f"有效器件:{ns}个","value":f"{ps}"},
                                    {"name":f"失效器件：{na-ns}个","value":f"{pa-ps}"}
                                ]
                            }]
                        })
                success.move(result)
                
                #热力图
                def freshimg():
                    heatimg.source = os.path.join(
                        chosenData,
                        'figure',f'{sdtype.value}-{spara.value}.jpg')
                    heatimg.update()
                with ui.element('div').classes('w-full') as heatmap:
                    with ui.row():
                        ui.space()
                        heatimg = ui.image(
                            os.path.join(chosenData,'figure','PMOS-Ion.jpg')
                        ).classes("figure")
                        ui.space()
                    with ui.row():
                        ui.space()
                        sdtype = ui.select(['PMOS','NMOS'],value='PMOS',on_change=freshimg)
                        spara = ui.select(['Ion','Ioff','OOR','Vth','Gm','SS','Fail'],
                                        value='Ion',on_change=freshimg)
                        ui.space()
                heatmap.move(result)    
                                                                        
            waiting.visible = False
            
            
            await asyncio.sleep(0.1)

            
        forceAna = partial(analysis,isforce = True)
        with ui.button_group():
            ui.button('☯️解析数据',on_click=analysis)
            ui.button('☯️重新解析数据',on_click=forceAna)

        pathLabel = ui.label(chosenData).on('change',classDir)
        ui.separator()
        with ui.row() as waiting:
            ui.spinner("bars",size='lg')
            ui.label('若长时间未显示结果，请刷新页面。')
        waiting.visible = False
        with ui.column().classes('w-full') as result:
            ui.label("Waiting to Analysis...")
        

app.native.window_args['resizable'] = False
app.native.settings['ALLOW_DOWNLOADS'] = True
'''ui.run(title="starATEData",
       native=True,
       window_size=(1200,900),
       fullscreen=False,
       reload=True,
       favicon='favicon.ico')
'''
ui.run(title="starATEData",favicon='🔯')